const net = require('net');
const { unknown, SUCCESS } = require('../database/common/constants');
const { getError, toLog } = require('../database/common/common');
const { transcode } = require('buffer');
class Socket {
    constructor() {

    }
    async init(ip, port) {
        this.server = new net.createServer();
        this.server.on('connection', async (client) => {

            client.on('data', async (msg) => { //接收client发来的信息
                let info = client.address();  //{ address: '127.0.0.1', family: 'IPv4', port: 44944 } 可以获取客户端的ip地址
                let get = null;
                try {
                    get = JSON.parse(msg.toString());

                } catch (error) {
                    throw ('BAD_REQUEST');
                }
                // resValue = iconv.decode(msg,'utf8');
                // 在这里校验用户名和密码
                let type = get.type;      //与客户端预先定义接口
                toLog("服务端收到的数据为 ", get);
                try {
                    switch (type) {
                        case 'sql':
                            //先判断是否有合法的签名 随后解析sql
                            await conn.checkSign(get.sign);
                            await sql.parse(get.data, get.sign);
                            break;
                        case 'login':
                            await conn.setUser(info, get.user, get.password);
                            break;
                        case 'trans':
                            await conn.checkSign(get.sign);
                            await trans.transParse(get.data, get.sign, get.id);
                        default:
                            this.response('UNKNOWN_ERROR', client);
                            break;
                    }
                } catch (err) {
                    this.response(err, client);
                }
            });

            client.on('error', function (e) { //监听客户端异常
                toLog('client error' + e);
                client.end();
            });

            client.on('close', function () {
                toLog(`客户端下线了`);
            });

            client.setTimeout(parseInt(ini.db.timeOut)); //从配置文件读取每个连接的超时时间
            client.on('timeout', () => {
                toLog('客户端超时了');
                client.end();
            });
        });
        this.server.listen(port, ip, function () {
            log.debug(`AvenirSQL运行在：${ip}:${port}`);
        });

    }


    //返回数据给客户端 兼容报错和正常的返回
    async response(type, client) {
        let res = null;
        if (typeof type == 'string') {
            res = getError(type);
            if (!res) {
                res = unknown;
            }
        } else {
            let code = type.code;
            let data = type.data;
            res = getError(code);
            if (!res) {
                res = unknown;
            }
            res.data = data;
        }
        client.write(JSON.stringify(res));
        //如果没有配置默认短连接

        if (ini.db.keepAlive != true) {
            toLog("主动踢掉客户端的连接");
            client.end();
        }
    }
}

module.exports = Socket;
